<?php
	/**
	 * 派送红包
	 */
    class SendMoneyToOther extends APIBase {
		
		public $tag = "SendMoneyToOther";
		public $isLogin = true;
		
		public function before() 
		{			
			$this->initMysql();
			return true;
		}

		public function logic() 
		{			
			
			if (!isset($this->param['send_money']))
			{
				$this->returnError(403, "send_money is must need");
			}
			else
			{
				$money_count = (int)$this->param['send_money'];
			
				if ( $money_count <= 0 )
				{
					$this->returnError(404, "send money must more than 0");
				}
			}
			
			$player = $this->data_redis->hMget("hu:{$this->uid}", array('money', 'user'));
				
			if ($player['money'] < $money_count)
			{
				$this->returnError(405, "send money more than self money");
			}
			
			$friend = array();
			
			
			if (!isset($this->param['friend_uid']))
			{
				$this->returnError(401, "friend_uid is must need");
			}
			else 
			{
				$friend_uid = (int)$this->param['friend_uid'];
				
				//查找缓存中是否有收红包玩家信息，如果没有就查询数据库
				$isExists = $this->data_redis->exists("hu:{$friend_uid}");			
				
				if (!$isExists ) 
				{										
					$row = $this->mysql->find("select * from player where id = $friend_uid");
					
					if (count($row) == 0) 
					{
						$this->returnError(402, 'user is not exist.');
					}
					
					$friend = $row[0];		

					//转移金币
					$player['money'] -= $money_count;
					$friend['money'] += $money_count;
					
					//更新数据库
					$where['id'] = $friend_uid;
					$sign  = $this->mysql->update('player', $friend, $where);
										
				}
				else 
				{	
					$friend = $this->data_redis->hMGet("hu:{$friend_uid}", array('money', 'user'));		

					//转移金币
					$player['money'] -= $money_count;
					$friend['money'] += $money_count;
					
					//更新缓存
					$this->data_redis->hMset("hu:{$friend_uid}", $friend);
				}
			}
			
						
			//更新缓存			
			$this->data_redis->hMset("hu:{$this->uid}", $player);			
			
			//通知玩家
			$title = "收到红包啦";
			$content = $player['user'] . "派发了包含" . $money_count . "金币的红包给你";
			$this->sendMessage($friend_uid, $title, $content);
			
			$title2 = "派送红包成功";
			$content2 = "成功派发了包含" . $money_count . "金币的红包给" . $friend['user'];
			$this->sendMessage($this->uid, $title2, $content2);
			
			$result = $this->data_redis->hMget("$this->uid", array('money'));
			
			$result['money'] = (int)$result['money'];
			
			$this->returnData($player, 0, "send money reward succ.\n");
		}
		
    	public function after() {
			$this->deinitDataRedis();
			$this->deinitMysql();
		}
    }
?>